import * as echarts from "echarts";
import { baseOptions } from "./config";
import { merge } from "lodash";

/**
 * 传入的需要挂载的dom id
 * @param {string} domId
 *
 * 需要初始化和更新的setOptions操作
 * @param {Object} options
 */
export default function ({
  domId = "",
  options = {},
  fn = function () {},
  isAutoMounted = true,
}) {
  let myECharts = null;

  const _useOptions = (_options) => {
    return merge({}, baseOptions, _options);
  };

  const updateEcharts = (__options) => {
    myECharts.setOption(_useOptions(__options));
  };

  const echartsInit = () => {
    myECharts = echarts.init(document.getElementById(domId), null, {
      locale: "ZH",
    });
    updateEcharts(options);
    window.addEventListener("resize", () => {
      // 自适应大小
      myECharts.resize();
    });

    myECharts.on("click", function (param) {
      fn.call(fn, param);
    });
  };
  if (isAutoMounted) {
    onMounted(() => {
      echartsInit();
    });
  } else {
    echartsInit();
  }

  return {
    myECharts,
    echartsInit,
    updateEcharts,
  };
}
